<?php

namespace App\Http\Controllers\Home;

use App\Models\Category;
use Illuminate\Http\Request;
use App\Models\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;

class IndexControllers extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //主页视图
        $originCategories = Category::orderBy('path')->get();
        $categories = $this->sortOutCategories($originCategories);
        $children = [];
        foreach ($categories as $c){
            $children[] = $c['children'];
        }
        return view('home/index/index')->with('categories', $categories)->with('children',$children);

    }

    /**
     * 递归整理类别数据，按级别整理结构
     * @param $originCategories
     * @param int $parentId
     */
    private function sortOutCategories($originCategories, $id = 0)
    {
        $categories = [];
        foreach ($originCategories as $c) {
            if ($c->parent_id == $id) {
                $children = $this->sortOutCategories($originCategories, $c->id);
                $c->children = $children;
                $categories[] = $c->toArray();
            }
        }
        return $categories;
    }
}
